<template>
    <el-popover
            placement="bottom"
            v-model:visible="visible"
            :width="width > 500 ? width : 500"
            trigger="click"
            @show="getDataList"
            @hide="isLoaded = false"
            :disabled="disabled || readonly"
    >
        <template #reference>
            <div class="input-wrap" ref="inputRef" @mouseover="showClearBtn" @mouseleave="hideClearBtn">

                <!--重写input输入框，监听数据-->
                <template v-if="rewriteInput">
                    <div class="ipt-box">
                        <input class="ipt" type="text" :placeholder="placeholder || '请选择'" :value="mValue" readonly :disabled="disabled">
                        <i class="iconfont icon-guanbi" v-show="isCloseBtn" @click.stop="clearValue"></i>
                    </div>
                </template>

                <el-input
                        v-else
                        :value="mValue"
                        :placeholder="placeholder || '请选择'"
                        readonly
                        :disabled="disabled"
                >
                    <template #suffix>
                        <div v-if="(!disabled && !readonly)">
                            <i class="iconfont icon-fangdajing" v-show="!isCloseBtn"></i>
                            <i class="iconfont icon-guanbi" v-show="isCloseBtn" @click.stop="clearValue"></i>
                        </div>
                    </template>
                </el-input>
            </div>
        </template>
        <div style="height: 360px;">
            <div v-if="isLoaded" v-loading="loading">
                <el-input style="width: 50%;margin-bottom: 10px;"
                          v-if="searchField"
                        v-model="searchValue" clearable
                        placeholder="请输入关键字搜索"
                          @keydown.enter="onSearch"
                >
                    <!--<template #suffix>
                        <i class="iconfont icon-fangdajing" v-show="!isCloseBtn"></i>
                        <i class="iconfont icon-guanbi" v-show="isCloseBtn" @click.stop="clearValue"></i>
                    </template>-->
                    <template #append>
                        <el-button @click="onSearch" >
                            <i class="iconfont icon-fangdajing"></i>
                        </el-button>
                    </template>
                </el-input>
                <el-table
                        class=""
                        :height="250"
                        border
                        :data="tableData"
                        size="small"
                        highlight-current-row
                        @current-change="handleCurrentChange"
                        @row-dblclick="handleDblclick"
                        ref="tableRef"
                        empty-text="暂无数据"
                >
                    <el-table-column v-for="item in cols" :prop="item.prop" :label="item.label" />

                </el-table>
                <div class="page-wrap"  >

                    <m-page
                            v-model:current-page="currentPage"
                            v-model:page-size="pageSize"
                            :total="total"
                            :pager-count="3"
                            small
                    />
                </div>
                <div class="btn-wrap">
                    <el-button type="primary" @click="selectValue">确定</el-button>
                </div>
            </div>
        </div>
    </el-popover>
</template>

<script setup>
    import {ref,onMounted,nextTick,defineEmits,defineProps,watch} from 'vue';
    import MPage from '@/components/common/Page/Page'

    const emit = defineEmits(['change']),
      props = defineProps({
        entityKey: { //主显示字段
          default: 'name'
        },
        value: {},
        readonly: {},
        disabled: {},
        placeholder: {},
        cols: {},
        url: {},
        param: {},
        searchField: {},
        rewriteInput: {}
      });
    let visible = ref(false),
      mValue = ref(''),
      width = ref(0),
      inputRef = ref(null),
      isCloseBtn = ref(false),
      isLoaded = ref(false),    //初始时不加载
      searchValue = ref('')

    //表格内容
    let tableRef = ref(null),
      // cols = ref([]),
      tableData = ref([]),  //表格数据
      currentRow = ref(),   //当前表格高亮行
      selectedRow = ref(),  //选中行
      loading = ref(false);
    //分页
    let currentPage = ref(1),
      pageSize = ref(10),
      total = ref(100);

    watch(()=>props.value,(val) => {
      mValue.value = val;
      console.log(val);
    },{immediate: true});
    /*监听分页*/
    watch([pageSize,currentPage],function ([a,b],[c,d]) {
      getDataList();
    })


    //搜索
    function onSearch(){
      if (currentPage.value !== 1){
        currentPage.value = 1;
      } else {
        getDataList();
      }
     /* let query = {};
      if (props.searchField){
        props.searchField.forEach(item => {
          query[item] = searchValue.value
        })
      }
      getDataList(query)*/
    }

    //获取表格数据
    function getDataList(){
      if (!props.url)return;
      // if (!isLoaded.value) isLoaded.value = true;
      isLoaded.value = true;
      loading.value = true;
      let query = {};
      if (props.searchField){
        props.searchField.forEach(item => {
          query[item] = searchValue.value
        })
      }

      let param = {
        'page.no': currentPage.value,
        'page.size': pageSize.value,
        ...props.param,
        ...query
      };
        props.url(param).then(res => {
        loading.value = false;
        if (!isLoaded.value) return;
        if (res.errcode != 0 ) return;
        let data = res.row
        tableData.value = data;
        total.value = res.total;
        //已选行，通过唯一标识判断，设置高亮
        let index = currentRow.value && data.findIndex(item => item.name === currentRow.value.name);
        tableRef.value.setCurrentRow(data[index])
      })
      /*setTimeout(()=>{
        loading.value = false;
        if (!isLoaded.value) return;
        let data = [
          {date: '2023-04-26',name: '李白',address:'青莲镇',id: 1},
          {date: '2023-04-26',name: '杜甫',address:'河南郑州巩义市站街镇南瑶湾村',id: 2},
        ];
        tableData.value = data;
        //已选行，通过唯一标识判断，设置高亮
        let index = currentRow.value && data.findIndex(item => item.name === currentRow.value.name);
        tableRef.value.setCurrentRow(data[index])
      },1000)*/
    }
    //单击表格行
    function handleCurrentChange(val){
      currentRow.value = val
    }

    //双击行
    function handleDblclick(val) {
      currentRow.value = val
      selectValue();
    }

    //选中行
    function selectValue() {
      if (!currentRow.value){
        console.log('请先选择数据！');
        return
      }
      selectedRow.value = currentRow.value;
      mValue.value = currentRow.value[props.entityKey];
      visible.value = false;
      emit('change',currentRow.value)
    }

    //显示清除按钮
    function showClearBtn(){
      isCloseBtn.value = !!mValue.value;
    }
    //隐藏清除按钮
    function hideClearBtn(){
      isCloseBtn.value = false;
    }
    //清除
    function clearValue(){
      mValue.value = '';
      selectedRow.value = '';
      emit('change',{})
    }

    onMounted(() => {
      nextTick(() => {
        width.value = inputRef.value.offsetWidth;
      })
    })
</script>

<style scoped lang="less">
.input-wrap {
    width: 100%;
    height: 100%;
    ::v-deep{
        .el-input__inner{
            cursor: pointer;
        }
    }
    .icon-guanbi{
        cursor: pointer;
    }
    .ipt-box{
        height: 100%;
        display: flex;
        align-items: center;
        .ipt{
            height: 100%;
            width: 100%;
        }
    }
}
    .page-wrap{
        padding-top: 6px;
    }
    .btn-wrap{
        display: flex;
        justify-content: flex-end;
    }

</style>
